package de.gwtprime.server.util;

import gwtupload.server.exceptions.UploadActionException;
import gwtupload.server.gae.AppEngineUploadAction;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.IOUtils;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.ServingUrlOptions;

/**
 * Upload image to the blob store and return an access url to that image
 * @author jan.pumpe
 *
 */
public class MyUploadAction extends AppEngineUploadAction{


	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * Logger
	 */
	private static Logger logger = Logger.getLogger(MyUploadAction.class.getName());

	@Override
	public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException {

		logger.info("Saving image to JDO datastore");
		System.out.println(sessionFiles.get(0).getName());
		
		String imageUrls = "";

		// Image service is needed to get url from blob
		ImagesService imagesService = ImagesServiceFactory.getImagesService();

		// Get a file service -> write the blob
		FileService fileService = FileServiceFactory.getFileService();

		// Iterate over the files and upload each one
		for(FileItem myFile : sessionFiles){

			InputStream imgStream = null;
			// construct our entity objects
			Blob imageBlob = null;


			// Create a new Blob file with mime-type "image/png"
			AppEngineFile file = null;

			FileWriteChannel writeChannel = null;
			try {

				// get input stream from file
				imgStream = myFile.getInputStream();
				imageBlob = new Blob(IOUtils.toByteArray(imgStream));
				
				
				// create empty app engine file with mime type of uploaded file e.g.: image/png, image/jpeg
				file = fileService.createNewBlobFile(myFile.getContentType(), myFile.getName());

				// Open a channel to write to it
				boolean lock = true;
				writeChannel = fileService.openWriteChannel(file, lock);

				// This time we write to the channel directly
				writeChannel.write(ByteBuffer.wrap(imageBlob.getBytes()));



			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				// Now finalize
				try {
					writeChannel.closeFinally();
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}


			// Get the url from the blob
			ServingUrlOptions suo = ServingUrlOptions.Builder.withBlobKey(fileService.getBlobKey(file)).secureUrl(true);
			imageUrls += imagesService.getServingUrl(suo);
			imageUrls = imageUrls.replaceFirst("0.0.0.0", "127.0.0.1");
			System.out.println(imageUrls);

		}
		return imageUrls ;
	}
}